package logic

import (
	"context"
	"fmt"
	"home-mgr/model"
	"math/rand"
	"strconv"

	"home-mgr/homerpc/homerpc"
	"home-mgr/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *homerpc.LoginRequest) (*homerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("tel=?", in.Tel).Find(&user)
	if user.ID == 0 {
		user = model.User{
			Tel:      in.Tel,
			Password: in.Password,
			Name:     "租客用户" + strconv.Itoa(rand.Intn(9000)),
			Img:      "https://pic.sogou.com/d?query=%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F&st=255&from=vr&did=3&phu=http%3A%2F%2Fpic.616pic.com%2Fys_img%2F00%2F16%2F93%2FZLtihzyGuu.jpg&rawQuery=%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F&vrExpId=&vrAdParams=&searchid=02219f92-3361-4b1a-859b-29ad897b49a2",
		}
		model.DB.Debug().Create(&user)
	}
	if user.ID != 0 {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码错误请重新输入")
		}
	}

	return &homerpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
